package person.twj.accountservice.feign.client;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import person.twj.accountservice.entity.AccountTbl;
import person.twj.accountservice.service.IAccountTblService;
import person.twj.common.feign.AccountFeignService;

@Slf4j
@RestController
@RequestMapping("/account")
public class AccountFeignServiceImpl implements AccountFeignService {
    private static final String SUCCESS = "SUCCESS";
    private static final String FAIL = "FAIL";

    @Autowired
    @Qualifier("accountTblServiceImpl")
    private IAccountTblService iAccountTblService;

    @Override
    @RequestMapping("/account")
    @GlobalTransactional
    public String account(@RequestParam("userId") String userId,
                          @RequestParam("money") int money,
                          @RequestParam("type") int type) {
        log.info("Account Service ... xid: " + RootContext.getXID());

        /*if (random.nextBoolean()) {
            throw new RuntimeException("this is a mock Exception");
        }*/
        AccountTbl account = iAccountTblService.getById(userId);
        log.info("原始ACCOUNT:"+ JSON.toJSONString(account));

        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.setSql(true, " money = money - {0} where user_id = {1}",
                new Object[] { money, userId });

        boolean result = iAccountTblService.update(wrapper);

        if(type==1){
            throw new RuntimeException("type=1");
        }
        if (result) {
            return SUCCESS;
        }
        return FAIL;
    }
}
